package com.servlet;

import com.beans.MemberInfo;
import com.beans.PageInfo;
import com.dao.MemberDao;
import com.util.PageUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "MemberServlet.do", value = "/MemberServlet.do")
public class MemberServlet extends HttpServlet {
    MemberDao memberDao = new MemberDao();
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String flag = request.getParameter("flag");
        if ("manage".equals(flag)){
            manage(request,response);
        }if ("deleteMember".equals(flag)){
            deleteMember(request,response);
        }
    }

    //删除会员
    private void deleteMember(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));

        memberDao.deleteMember(id);
        request.setAttribute("msg","<script>alert('删除成功')</script>");
        this.manage(request,response);
    }

    private void manage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String memberNo = request.getParameter("memberNo");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        System.out.println(memberNo);
        System.out.println(beginDate);
        System.out.println(endDate);
        int pageSize = 5;
        int rowCount = memberDao.getMemberCount(memberNo,beginDate,endDate);
        int pageIndex = 1;
        String pageIndexstr = request.getParameter("pageIndex");
        if(pageIndexstr !=null&&pageIndexstr!="") {
            pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
            if(pageIndex>((rowCount+pageSize-1)/pageSize)) {
                pageIndex=((rowCount+pageSize-1)/pageSize);
            }
        }

        PageInfo page = PageUtil.getPageInfo(pageSize, rowCount, pageIndex);

        List<MemberInfo> memberList = memberDao.getMemberList(memberNo,beginDate,endDate,page);

        request.setAttribute("memberNo",memberNo);
        request.setAttribute("beginDate",beginDate);
        request.setAttribute("endDate",endDate);
        request.setAttribute("page",page);
        request.setAttribute("memberList",memberList);

        request.getRequestDispatcher("/member/member_manage.jsp").forward(request,response);
    }
}
